<?php
/* 
 * Copyright (c) 2018-2021  * 
 * 创建时间：2021-04-24 06:14
 *
 * 项目：upload  -  $  - levssqController.php
 *
 * 作者：liwei 
 */


namespace modules\levbdu\controllers;

!defined('INLEV') && exit('Access Denied LEV');

use Lev;
use lev\base\Controllerv;
use lev\base\Viewv;
use lev\helpers\UserHelper;
use lev\helpers\UserLoginModelHelper;
use lev\widgets\login\loginWidget;
use modules\levbdu\helpers\levbduSetHelper;
use modules\levbdu\table\bduHelper;

class DefaultController extends Controllerv {

    /**
     * Renders the index view for the module
     */
    public function actionIndex()
    {

        Lev::$app['title'] = '切换账号';

        //Lev::$app['openLoginScreen'] = true;

        Viewv::render('default/index', Lev::$app['uid'] >0 ? [
            'bdu'  => Lev::stripTags(Lev::opCookies('__bdu', null, -1)),
            'bdid' => floatval(Lev::opCookies('__bdid', null, -1)),
        ] : ['bdu'  => '', 'bdid'=>'']);

    }

    public static function actionAjax() {
        $limit = 15;
        if (Lev::$app['uid'] <1) {
            $lists = [];
        }else {
            $lists = bduHelper::myBdus(Lev::$app['uid'], $limit);
        }
        if (empty($lists)) {
            $not = 1;
            $htms = '';
        }else {
            $not = count($lists) < $limit ? 1 : 0;
            $users = UserLoginModelHelper::getUsers($uids = Lev::getArrayColumn($lists, ['bduid']));
            empty(Lev::$app['LevAPP']) && $users += UserHelper::getUsers($uids);
            $htms = Viewv::renderPartial('default/ajax', [
                'lists' => $lists,
                'users' => $users,
            ]);
        }

        echo json_encode(Lev::responseMsg(1, '', ['htms'=>$htms, 'not'=>$not]));
    }

    public static function actionDelbdu() {
        parent::csrfValidation();
        echo json_encode(static::Delbdu());
    }
    public static function Delbdu() {
        if (Lev::$app['uid'] <1) {
            return Lev::responseMsg(-5, '');
        }
        $bdInfo = bduHelper::bdInfo(Lev::$app['uid']);
        $opid = floatval(Lev::GPv('opid'));
        $opInfo = bduHelper::findOne(['id'=>$opid]);
        if ($opInfo && ($bdInfo['uid'] == $opInfo['uid'])) {
            bduHelper::delete(['id'=>$opid]);
            return Lev::responseMsg();
        }
        return Lev::responseMsg(-402, '用户未绑定');
    }

    public static function actionLogin() {
        parent::csrfValidation();
        echo json_encode(static::bduLogin());
    }
    public static function bduLogin() {
        if (Lev::$app['uid'] <1) {
            return Lev::responseMsg(-5, '');
        }
        $bdInfo = bduHelper::bdInfo(Lev::$app['uid']);
        $uid = floatval(Lev::GPv('uid'));
        if (
            bduHelper::findOne(['uid'=>$uid, 'bduid'=>$bdInfo['uid'], 'status'=>0], 'id') ||
            bduHelper::findOne(['bduid'=>$uid, 'uid'=>$bdInfo['uid'], 'status'=>0], 'id')
        ) {
            $msg = UserHelper::setLogin(['uid'=>$uid]);
            return $msg['status'] <1 ? $msg : Lev::responseMsg(1, '切换成功');
        }
        return Lev::responseMsg(-502, '用户未绑定', [$uid]);
    }

    public static function actionAddBdu() {
        parent::csrfValidation();

        Lev::$app['title'] = '添加切换账号';

        $bdu = Lev::stripTags(Lev::GPv('bdu'));
        $bdid = floatval(Lev::GPv('bdid'));
        if ($bdu || $bdid) {
            echo json_encode(static::SaveBdu($bdid, $bdu));
        }else {
            echo json_encode(static::AddBdu());
        }
    }
    public static function AddBdu() {

        if (Lev::$app['uid'] <1) {
            return Lev::responseMsg(-5, '');
        }

        $bdu = Lev::$app['timestamp'];

        $groupids = levbduSetHelper::groupids();
        if ($groupids && in_array(Lev::$app['groupid'], $groupids)) {
            return Lev::responseMsg(-999, '您所在的用户组禁止添加');
        }

        $maxbdu = levbduSetHelper::maxbdu();
        if ($maxbdu) {
            if ($maxbdu <1) {
                return Lev::responseMsg(-1001, '最大可添加数量为：'.$maxbdu);
            }
            $res = bduHelper::myBdus(Lev::$app['uid'], $maxbdu);
            if (count($res) >= $maxbdu) {
                return Lev::responseMsg(-1002, '数量已达上限');
            }
        }

        $ck = bduHelper::findOne(['uid'=>Lev::$app['uid'], 'bduid'=>0]);
        $data = ['uid'=>Lev::$app['uid'], 'status'=>2, 'addtime'=>$bdu];
        if ($ck) {
            $bdid = $ck['id'];
            bduHelper::update($data, ['id'=>$ck['id']]);
        }else {
            $bdid = bduHelper::insert($data, true);
        }

        //Lev::actionControllerAction('login', 'exit');
        //LoginController::actionExit();

        UserHelper::doLogout();
        Lev::opCookies('__bdu', md5($bdu.levbduSetHelper::bdupwd()), 300);
        Lev::opCookies('__bdid', $bdid, 300);
        loginWidget::setLoginReferer(Lev::toReRoute(['/', 'id'=>'levbdu']));
        Lev::setNotices('成功登陆后自动添加切换账号', true);
        return Lev::responseMsg(1, '', ['_csrf'=>Lev::getCsrf(), 'location'=>Lev::toReRoute(['/', 'id'=>'levbdu'])]);
    }

    public static function SaveBdu($bdid, $bdu) {
        if (Lev::$app['uid'] <1) {
            return Lev::responseMsg(-5, '');
        }

        $ck = bduHelper::findOne(['id'=>$bdid]);
        if (empty($ck) || $ck['status'] !=2 || $bdu != md5($ck['addtime'].levbduSetHelper::bdupwd()) || $ck['addtime'] < Lev::$app['timestamp'] - 300) {
            return Lev::responseMsg(-2001, '错误的切换账号绑定');
        }

        return bduHelper::SaveBdu($bdid, $ck['uid']);
    }

}